package com.zidian.study.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;

import com.google.android.gms.auth.firstparty.shared.FACLConfig;
import com.zidian.study.adapter.InteractionRecyclerAdapter;
import com.zidian.study.bean.QuestionListBean;
import com.zidian.study.globa.Constant;
import com.zidian.study.globa.ToolBarActivity;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ToastUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import com.zidian.student.trucks.R;

/**
 * Created by Administrator on 2016/8/24 0024.
 * 提问列表
 */
public class InteractionAskListActivity extends ToolBarActivity {

    public SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private ImageButton questionAdd;


    boolean isLoading;
    private List<QuestionListBean.DataBean> data = new ArrayList<>();
    private InteractionRecyclerAdapter adapter = new InteractionRecyclerAdapter(this, data);
    private Handler handler = new Handler();
    private int startrow = 1;
    private boolean isRefreshing = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_ask);
        setContentView(R.layout.activity_interaction_ask);
        setTitle("提问");
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_widget);
        recyclerView = (RecyclerView) findViewById(R.id.list);
        questionAdd = (ImageButton) findViewById(R.id.toolbar_add);

        initView();
        initData();
    }

    public void initView() {


        swipeRefreshLayout.setColorSchemeResources(R.color.green);

        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                isRefreshing = true;
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        data.clear();
                        startrow = 1;
                        isRefreshing = true;
                        getData(startrow + "");
                    }
                }, 2000);
            }
        });
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isRefreshing) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);


            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");

                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");

                    boolean isRefreshing = swipeRefreshLayout.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startrow++;
                                getData(startrow + "");
                                Log.d("test", "load more completed");
                                isLoading = false;
                            }
                        }, 1000);
                    }
                }
            }
        });


        //添加点击事件
        adapter.setOnItemClickListener(new InteractionRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Log.d("test", "item position = " + position);
                Intent intent = new Intent();
                intent.setClass(context, InteractionAskDetailActivity.class);
                intent.putExtra("askId", data.get(position).getIssueId());
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

        questionAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(InteractionQuestionAddActivity.class);
            }
        });


    }


    public void initData() {
        getData(startrow + "");

    }

    /**
     * 获取测试数据
     */
    private void getData(String startrow) {


        String loginUrl = Constant.URL_GOAL + "issueStudent/selectIssue";
        HashMap<String, String> map = new HashMap<>();
        map.put("startrow", startrow);
        map.put("pageSize", "10");
        map.put("token", GetUserInfo.getToken(context));
        map.put("studentId", GetUserInfo.getStudentId(context));

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
                swipeRefreshLayout.setRefreshing(false);
                isRefreshing = false;
            }

            @Override
            public void onResponse(String response, int id) {
                swipeRefreshLayout.setRefreshing(false);
                isRefreshing = false;
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(context, "获取问题列表失败！");
                        return;
                    }

                } catch (JSONException e) {

                }

                Log.e("T", response);

                Gson gson = new Gson();
                QuestionListBean model = gson.fromJson(response, QuestionListBean.class);
                if (model.isSuccess()) {
                    if (model.getData().size() < 10) {
                        isLoading = true;
                        adapter.setHasMore(false);
                    } else {
                        isLoading = false;
                        adapter.setHasMore(true);
                    }
                    data.addAll(model.getData());
                    adapter.notifyDataSetChanged();
                    adapter.notifyItemRemoved(adapter.getItemCount());
                }
            }
        });

    }
}
